package configmap

import (
	"context"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"kubeimooc/global"
	configmapres "kubeimooc/model/configmap/response"
	"strings"
)
import configmapreq "kubeimooc/model/configmap/request"

type ConfigMapService struct {
}

/*
*
获取configmap详情
*/
func (c *ConfigMapService) GetConfigMapDetail(namespace string, name string) (cm configmapres.ConfigMap, err error) {
	configMapK8s, err := global.KubeConfigSet.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, metav1.GetOptions{})
	if err != nil {
		return configmapres.ConfigMap{}, err
	}
	cm = configConvert.GeCmReqDetail(*configMapK8s)
	return //默认返回那个
}

/*
*
获取configmap的list
*/
func (c *ConfigMapService) GetConfigMapList(namespace string, keyword string) (cm []configmapres.ConfigMap, err error) {
	configMapListK8s, errK8s := global.KubeConfigSet.CoreV1().ConfigMaps(namespace).List(context.TODO(), metav1.ListOptions{})
	if errK8s != nil {
		err = errK8s
		return
	}
	list := make([]configmapres.ConfigMap, 0) //这个必须初始化
	for _, item := range configMapListK8s.Items {
		if !strings.Contains(item.Name, keyword) {
			continue
		}
		reqItem := configConvert.GeCmReqItem(item)
		list = append(list, reqItem)
	}
	return list, nil
}

/*
*
删除configmap
*/
func (c ConfigMapService) DeleteConfigMap(ns string, name string) error {
	return global.KubeConfigSet.CoreV1().ConfigMaps(ns).Delete(context.TODO(), name, metav1.DeleteOptions{})
}

/*
*
创建configmap
*/
func (c *ConfigMapService) CreateOrUpdateConfigMap(configReq configmapreq.ConfigMap) error {
	k8sConfigMap := configConvert.CmReq2K8sConvert(configReq)
	ctx := context.TODO()
	_, errSearch := global.KubeConfigSet.CoreV1().ConfigMaps(k8sConfigMap.Namespace).Get(ctx, configReq.Name, metav1.GetOptions{})
	if errSearch == nil {
		//进行更新
		_, err := global.KubeConfigSet.CoreV1().ConfigMaps(k8sConfigMap.Namespace).Update(ctx, k8sConfigMap, metav1.UpdateOptions{})
		if err != nil {
			return err
		}
	} else {
		//进行创建
		_, err := global.KubeConfigSet.CoreV1().ConfigMaps(k8sConfigMap.Namespace).Create(ctx, k8sConfigMap, metav1.CreateOptions{})
		if err != nil {
			return err
		}
	}
	return nil
}
